import { defineStore } from "pinia";
import { store } from "/@/store";
// import { getBtnAuthByRouteName } from "/@/api/mock";
import router, { constantRoutesArr, ascending } from "/@/router/index";
import { postResourceAuth } from "/@/api/resource";
import { getProjectResourceAuth } from "/@/api/projects";
import { reportLog } from "/@/api/report";
import { storageLocal } from "/@/utils/storage";
import { identifyHowxm } from "howxm-js";
import { getOsInfo, getBrowserInfo } from "/@/utils/report";

import axios from "axios";

export const usePermissionStore = defineStore({
  id: "pure-permission",
  state: () => ({
    constantRoutes: constantRoutesArr, //静态路由
    wholeRoutes: [],
    rootRoutes: [], // 一级路由
    buttonAuth: [],
    userName: "",
    userId: ""
  }),
  actions: {
    asyncActionRoutes(routes) {
      if (this.wholeRoutes.length > 0) return;
      // 之前的逻辑：如果根节点设置为不可见，则子目录也不可见；
      // 变更为：子目录状态不受父节点影响，军根据其自身的shouLink判断是否显示或者隐藏
      function getRoute(route) {
        const filterRoute = [];
        route.forEach(v => {
          if (v.children && v.children.length) {
            v.children = v.children.filter(c => c.meta?.showLink);
            if (!v.meta?.showLink) {
              v.children.forEach(i => {
                filterRoute.push(i);
              });
            } else {
              filterRoute.push(v);
            }
          } else {
            v.meta?.showLink && filterRoute.push(v);
          }
        });
        return filterRoute;
      }

      this.wholeRoutes = getRoute(
        ascending(this.constantRoutes.concat(routes))
      );

      // this.wholeRoutes = ascending(this.constantRoutes.concat(routes)).filter(
      //   v => {
      //     if (v.children) {
      //       v.children = v.children.filter(c => c.meta?.showLink);
      //     }
      //     return v.meta?.showLink;
      //   }
      // );

      // 原来是重route.meta中获取权限
      // const getButtonAuth = (arrRoutes: Array<string>) => {
      //   if (!arrRoutes || !arrRoutes.length) return;
      //   arrRoutes.forEach((v: any) => {
      //     if (v.meta && v.meta.authority) {
      //       this.buttonAuth.push(...v.meta.authority);
      //     }
      //     if (v.children) {
      //       getButtonAuth(v.children);
      //     }
      //   });
      // };
      //
      // getButtonAuth(this.wholeRoutes);
    },
    // setUserName(payload) {
    //   this.userName = payload;
    // },
    getRootMenu(routes) {
      this.rootRoutes = routes;
    },

    async changeMenu(routes) {
      // await this.resetSetting();
      await this.getRootMenu(routes);
    },

    async changeSetting(routes) {
      await this.resetSetting();
      await this.asyncActionRoutes(routes);
    },

    // 重置路由及权限
    async resetSetting() {
      this.wholeRoutes = [];
      this.buttonAuth = [];
      // this.rootRoutes = [];
    },

    // 重置路由
    async clearRoute(routes) {
      await this.resetRoute();
      await this.asyncActionRoutes(routes);
    },

    // 重置路由及权限
    async resetRoute() {
      this.wholeRoutes = [];
    },

    // ldap 登录处理
    async ldapLogin(code, state) {
      let authorization = "";
      if (storageLocal.getItem("info")) {
        authorization = storageLocal.getItem("info")?.accessToken;
      }
      const baseUrl = import.meta.env.VITE_BASE_URL;

      const sourceUrl = `${baseUrl}/snow-admin/sysResource/resourceAuth`;
      const headerConfig = {
        code: code,
        state: state,
        loginMethod: "PC"
      };
      if (authorization) {
        //@ts-ignore
        headerConfig.Authorization = authorization;
      }
      try {
        const res = await axios.post(
          sourceUrl,
          { groupUrl: "/projects/manage/space" },
          {
            headers: headerConfig
          }
        );

        console.log(res.headers, "response");

        if (res.headers.name) {
          const info = {
            username: decodeURI(res.headers?.username),
            name: decodeURI(res.headers?.name),
            userId: res.headers?.userid,
            accessToken: res.headers?.token
          };
          this.userName = decodeURI(res.headers?.name);
          this.userId = decodeURI(res.headers?.userid);
          storageLocal.setItem("info", info);
          // 浩客identify 用户身份信息传递
          identifyHowxm({
            uid: info.username, // 用户唯一ID, 默认字段, 必填，string 类型
            name: info.name // 名称，默认字段，非必填，string 类型
          });
        }

        console.log(storageLocal.getItem("info"), "info");

        if (res.data?.code === 200) {
          this.buttonAuth =
            res.data.data.length &&
            res.data.data.map(item => {
              return item.resourceKey;
            });

          return true;
        } else {
          this.buttonAuth.length = 0;
          return false;
        }
      } catch (error) {
        console.log(error.response);
        const code = error?.response?.status;
        if ([401, 403].includes(code)) {
          storageLocal.removeItem("info");

          // router.replace({
          //   path: "/login"
          //   // query: { redirect: location.href }
          // });
          await this.ldapLogin(headerConfig.code, headerConfig.state);
        }
      }
    },

    async getBtnAuth(path: string, query?: any) {
      // 现在是直接根据下一次要进入页面的name去后台查询权限
      if (path === "/projects/manage/space" && query.code) {
        await this.ldapLogin(query.code, query.state);
        await this.getSysUserInfo(path);
      } else {
        try {
          let res = [];
          if (
            path.indexOf("projectsB") > -1 ||
            path.indexOf("projectsA") > -1 ||
            path.indexOf("projectsS") > -1
          ) {
            let sectionId = "";
            if (path.indexOf("projectsB") > -1) {
              sectionId = "B";
            } else if (path.indexOf("projectsA") > -1) {
              sectionId = "A";
            } else if (path.indexOf("projectsS") > -1) {
              sectionId = storageLocal.getItem("sectionInfo")?.id + "";
            }
            res = await getProjectResourceAuth({
              groupUrl: path,
              projectManageId: storageLocal.getItem("projectInfo")?.id,
              sectionId: sectionId
            });
          } else {
            res = await postResourceAuth({ groupUrl: path });
          }
          await this.getSysUserInfo(path);
          if (res.code === 200) {
            this.buttonAuth =
              res.data.length &&
              res.data.map(item => {
                return item.resourceKey;
              });
            return true;
          } else {
            this.buttonAuth.length = 0;
            return false;
          }
        } catch (error) {
          const code = error?.response?.status;
          if ([401, 403].includes(code)) {
            storageLocal.removeItem("info");
            router.replace({
              path: "/login"
              // query: { redirect: location.href }
            });
            // }
          }
        }
      }
    },

    async getSysUserInfo(path) {
      const osName = getOsInfo();
      let userId = "";
      if (storageLocal.getItem("info")) {
        userId = storageLocal.getItem("info")?.username;
      }
      const browserName = getBrowserInfo().toString().split("/")[0];
      const browserVersionName = getBrowserInfo().toString().split("/")[1];
      const params = {
        userId: userId,
        os: osName,
        browser: `${browserName}-${browserVersionName}`,
        pageView: path,
        logLevel: "info",
        content: ""
      };
      try {
        await reportLog(params);
        // console.log(res, "res");
      } catch (error) {
        console.log(error);
      }
    }
  }
});

export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
